<template>
  <div class="profile-page">
    <div class="profile-header">
      <h2>个人中心</h2>
    </div>

    <div class="profile-content">
      <!-- 个人信息区域 -->
      <div class="profile-section">
        <div class="section-header">
          <h3>基本信息</h3>
        </div>
        <div class="section-content">
          <div class="loading" v-if="userProfileLoading">
            <p>加载中...</p>
          </div>
          <div class="info-grid" v-else>
            <div class="avatar-item">
              <div class="avatar-preview">
                <div class="avatar-container" @click="triggerAvatarUpload">
                  <img
                    :src="userProfile.avatar_url || defaultAvatar"
                    alt=""
                    class="avatar-image"
                    @error="handleAvatarError"
                  />
                  <div class="avatar-overlay">
                    <span class="upload-icon">📷</span>
                    <span class="upload-text">点击更换头像</span>
                  </div>
                </div>
                <input
                  type="file"
                  ref="avatarInput"
                  accept="image/*"
                  @change="handleAvatarChange"
                  style="display: none"
                />
                <div class="avatar-controls" v-if="selectedAvatar">
                  <button class="save-avatar-btn" @click="saveAvatar" :disabled="isUploadingAvatar">
                    {{ isUploadingAvatar ? '上传中...' : '保存头像' }}
                  </button>
                  <button class="cancel-avatar-btn" @click="cancelAvatarUpload">取消</button>
                  <p class="upload-hint">支持 JPG、PNG 格式，文件大小不超过 2MB</p>
                </div>
              </div>
            </div>

            <div class="info-item">
              <span class="label">用户名：</span>
              <span class="value">{{ userProfile.username || '未设置' }}</span>
            </div>
            <div class="info-item">
              <span class="label">邮箱：</span>
              <span class="value">{{ userProfile.email || '未设置' }}</span>
            </div>
            <div class="info-item">
              <span class="label">手机号：</span>
              <span class="value">{{ userProfile.mobile || '未设置' }}</span>
            </div>
            <div class="info-item">
              <span class="label">性别：</span>
              <span class="value">{{ genderText }}</span>
            </div>
            <div class="info-item">
              <span class="label">生日：</span>
              <span class="value">{{ userProfile.birthday || '未设置' }}</span>
            </div>
          </div>
          <div class="section-footer">
            <button class="edit-btn" @click="showEditProfileDialog">修改个人信息</button>
          </div>
        </div>
      </div>

      <!-- 地址管理区域 -->
      <div class="profile-section">
        <div class="section-header">
          <h3>收货地址</h3>
        </div>
        <div class="section-content">
          <div class="loading" v-if="addressLoading">
            <p>加载中...</p>
          </div>
          <div class="address-list" v-else>
            <div
              v-for="address in addressList"
              :key="address.address_id"
              class="address-item"
              :class="{ 'default-address': address.is_default }"
            >
              <div class="address-header">
                <span class="name">{{ address.receiver_name }}</span>
                <span class="mobile">{{ address.receiver_mobile }}</span>
                <span v-if="address.is_default" class="default-tag">默认</span>
              </div>
              <div class="address-detail">
                {{ formatFullAddress(address) }}
              </div>
              <div class="address-actions">
                <button
                  v-if="!address.is_default"
                  class="set-default-btn"
                  @click="setDefaultAddress(address.address_id)"
                >
                  设为默认
                </button>
                <button class="edit-address-btn" @click="editAddress(address.address_id)">
                  编辑
                </button>
                <button class="delete-address-btn" @click="deleteAddress(address.address_id)">
                  删除
                </button>
              </div>
            </div>

            <div v-if="addressList.length === 0" class="no-address">
              <p>暂无收货地址</p>
            </div>
          </div>

          <div class="section-footer">
            <button class="edit-btn" @click="addNewAddress">
              <i class="el-icon-plus"></i> 添加新地址
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 个人信息编辑弹框 -->
  <el-dialog v-model="editProfileDialogVisible" title="修改个人信息" width="500px">
    <el-form :model="profileForm" :rules="profileRules" ref="profileFormRef" label-width="80px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="profileForm.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="profileForm.email" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="profileForm.mobile" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="profileForm.gender" placeholder="请选择性别">
          <el-option label="未知" :value="0"></el-option>
          <el-option label="男" :value="1"></el-option>
          <el-option label="女" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="生日" prop="birthday">
        <el-date-picker
          v-model="profileForm.birthday"
          type="date"
          placeholder="请选择生日"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editProfileDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveProfile" :loading="isSaving">保存</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 地址编辑弹框 -->
  <AddressForm
    v-model:visible="addressFormVisible"
    :title="addressFormTitle"
    :address="editingAddress"
    @success="handleAddressSuccess"
  />
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onActivated, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/useAuthStore'
import { addressApi, type Address } from '@/api/address'
import { userApi, type UserProfile, getGenderText, formatDateTime } from '@/api/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import AddressForm from '@/components/user/AddressForm.vue'
import type { FormInstance, FormRules } from 'element-plus'

// 路由和状态管理
const router = useRouter()
const userStore = useAuthStore()

// 表单引用
const profileFormRef = ref<FormInstance>()

// 响应式数据
const defaultAvatar = ref('')
const defaultAddress = ref<Address | null>(null)
const addressList = ref<Address[]>([])
const userProfile = ref<UserProfile>({
  user_id: 0,
  username: '',
  email: '',
  mobile: '',
  gender: 0,
  avatar: '',
  avatar_url: '',
  birthday: '',
  status: 1,
  last_login_time: '',
  is_staff: false,
  is_active: true,
  date_joined: '',
})

const loading = ref(false)
const userProfileLoading = ref(false)
const addressLoading = ref(false)
const isSaving = ref(false)
const isUploadingAvatar = ref(false)
const editProfileDialogVisible = ref(false)

// 头像上传相关
const selectedAvatar = ref<File | null>(null)
const avatarInput = ref<HTMLInputElement | null>(null)

// 地址表单相关
const addressFormVisible = ref(false)
const addressFormTitle = ref('添加地址')
const editingAddress = ref<Address | null>(null)

// 个人信息表单数据
const profileForm = reactive({
  username: '',
  email: '',
  mobile: '',
  gender: 0,
  birthday: '',
})

// 表单验证规则
const profileRules = reactive<FormRules>({
  username: [
    { required: false, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' },
  ],
  email: [
    { required: false, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
  ],
  mobile: [
    { required: false, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号', trigger: 'blur' },
  ],
  gender: [{ required: false, message: '请选择性别', trigger: 'change' }],
  birthday: [{ required: false, message: '请选择生日', trigger: 'change' }],
})

// 计算属性
const genderText = computed(() => {
  return getGenderText(userProfile.value.gender)
})

// 方法
const formatDate = (dateString?: string) => {
  if (!dateString) return ''
  return formatDateTime(dateString)
}

const formatFullAddress = (address: Address) => {
  return `${address.province}${address.city}${address.district}${address.detailed_address}`
}

const handleAvatarError = (event: Event) => {
  const img = event.target as HTMLImageElement
  // 防止重复尝试加载失败的图片
  if (img.src !== defaultAvatar.value) {
    // 当图片加载失败时，设置为空字符串，让CSS处理默认显示
    img.src = ''
  }
}

const fetchUserProfile = async () => {
  userProfileLoading.value = true
  try {
    const profile = await userApi.getUserProfile()
    userProfile.value = profile
  } catch (error) {
    console.error('获取用户信息失败:', error)
  } finally {
    userProfileLoading.value = false
  }
}

const fetchAddressList = async () => {
  addressLoading.value = true
  try {
    console.log('开始获取个人中心地址列表...')
    // 获取地址列表
    const response = await addressApi.getAddressList()

    // 详细的调试信息
    console.log('Profile Address API Response:', response)
    console.log('Response type:', typeof response)

    // 确保响应和results存在
    if (response && typeof response === 'object' && 'results' in response) {
      console.log('Results exist:', Array.isArray(response.results))
      console.log('Results count:', response.results?.length || 0)

      if (Array.isArray(response.results)) {
        console.log('Address results:', response.results)
        addressList.value = response.results

        // 找到默认地址
        const defaultAddr = response.results.find((addr) => addr.is_default)
        defaultAddress.value = defaultAddr || null

        // 如果没有默认地址但有地址列表，使用第一个地址
        if (!defaultAddress.value && response.results.length > 0) {
          defaultAddress.value = response.results[0]
        }

        console.log('个人中心地址列表设置成功，数量:', addressList.value.length)
      } else {
        console.warn('Results is not an array, initializing as empty array')
        addressList.value = []
        defaultAddress.value = null
      }
    } else {
      console.log('No address data or invalid response structure')
      // 如果没有数据，初始化为空数组
      addressList.value = []
      defaultAddress.value = null
    }

    console.log('个人中心最终地址列表:', addressList.value)
    console.log('个人中心默认地址:', defaultAddress.value)
  } catch (error) {
    console.error('获取地址列表失败:', error)
    ElMessage.error('获取地址信息失败: ' + (error as Error).message)
    // 出错时也初始化为空数组
    addressList.value = []
    defaultAddress.value = null
  } finally {
    addressLoading.value = false
    console.log('个人中心地址列表加载完成')
  }
}

const setDefaultAddress = async (addressId: string) => {
  try {
    // 将字符串ID转换为数字，因为API需要数字ID
    const id = parseInt(addressId, 10)
    if (isNaN(id)) {
      ElMessage.error('地址ID无效')
      return
    }
    await addressApi.setDefaultAddress(id)
    ElMessage.success('设置默认地址成功')
    // 重新获取地址列表
    fetchAddressList()
  } catch (error) {
    console.error('设置默认地址失败:', error)
    ElMessage.error('设置默认地址失败')
  }
}

const editAddress = (addressId: string) => {
  // 找到要编辑的地址
  const address = addressList.value.find((addr) => addr.address_id === addressId)
  if (address) {
    editingAddress.value = address
    addressFormTitle.value = '编辑地址'
    addressFormVisible.value = true
  }
}

const deleteAddress = async (addressId: string) => {
  ElMessageBox.confirm('确定要删除这个地址吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        // 将字符串ID转换为数字，因为API需要数字ID
        const id = parseInt(addressId, 10)
        if (isNaN(id)) {
          ElMessage.error('地址ID无效')
          return
        }
        await addressApi.deleteAddress(id)
        ElMessage.success('删除成功')
        // 重新获取地址列表
        fetchAddressList()
      } catch (error) {
        console.error('删除地址失败:', error)
        ElMessage.error('删除地址失败')
      }
    })
    .catch(() => {
      // 用户取消删除
    })
}

const addNewAddress = () => {
  editingAddress.value = null
  addressFormTitle.value = '添加地址'
  addressFormVisible.value = true
}

const handleAddressSuccess = () => {
  // 地址操作成功后刷新地址列表
  fetchAddressList()
}

// 显示编辑个人信息弹框
const showEditProfileDialog = () => {
  // 初始化表单数据
  profileForm.username = userProfile.value.username
  profileForm.email = userProfile.value.email
  profileForm.mobile = userProfile.value.mobile
  profileForm.gender = userProfile.value.gender
  profileForm.birthday = userProfile.value.birthday
  editProfileDialogVisible.value = true
}

// 保存个人信息
const saveProfile = async () => {
  if (!profileFormRef.value) return

  await profileFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return

    try {
      isSaving.value = true

      // 构造更新参数，只包含有值的字段
      const params: Record<string, any> = {}
      if (profileForm.username) params.username = profileForm.username
      if (profileForm.email) params.email = profileForm.email
      if (profileForm.mobile) params.mobile = profileForm.mobile
      if (profileForm.gender !== undefined) params.gender = profileForm.gender
      if (profileForm.birthday) params.birthday = profileForm.birthday

      // 调用更新用户信息接口
      await userApi.updateUserProfile(params)

      // 更新用户信息
      await fetchUserProfile()

      // 关闭弹框
      editProfileDialogVisible.value = false

      ElMessage.success('个人信息更新成功')
    } catch (error) {
      console.error('更新个人信息失败:', error)
      ElMessage.error('更新个人信息失败: ' + (error as Error).message)
    } finally {
      isSaving.value = false
    }
  })
}

// 头像上传相关方法
const triggerAvatarUpload = () => {
  if (avatarInput.value) {
    avatarInput.value.click()
  }
}

const handleAvatarChange = (event: Event) => {
  const input = event.target as HTMLInputElement
  if (input.files && input.files[0]) {
    const file = input.files[0]

    // 验证文件类型
    if (!file.type.startsWith('image/')) {
      ElMessage.error('请选择图片文件')
      return
    }

    // 验证文件大小 (2MB)
    if (file.size > 2 * 1024 * 1024) {
      ElMessage.error('文件大小不能超过 2MB')
      return
    }

    selectedAvatar.value = file
  }
}

const saveAvatar = async () => {
  if (!selectedAvatar.value) {
    ElMessage.warning('请先选择头像图片')
    return
  }

  try {
    isUploadingAvatar.value = true

    // 创建 FormData 对象，使用avatar字段名
    const formData = new FormData()
    formData.append('avatar', selectedAvatar.value)

    // 调用更新用户信息接口（通过info接口更新头像）
    await userApi.updateUserProfileWithAvatar(formData)

    // 更新用户信息
    await fetchUserProfile()

    // 更新认证存储中的头像URL
    if (userStore.user) {
      userStore.user.avatar = userProfile.value.avatar
      userStore.user.avatar_url = userProfile.value.avatar_url
    }

    ElMessage.success('头像更新成功')
    selectedAvatar.value = null
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败: ' + (error as Error).message)
  } finally {
    isUploadingAvatar.value = false
  }
}

// 取消头像上传
const cancelAvatarUpload = () => {
  selectedAvatar.value = null
  if (avatarInput.value) {
    avatarInput.value.value = ''
  }
}

// 刷新所有数据
const refreshAllData = () => {
  fetchUserProfile()
  fetchAddressList()
}

// 生命周期
onMounted(() => {
  refreshAllData()
})

// 当页面被激活时也刷新数据（解决从其他页面返回时数据不更新的问题）
onActivated(() => {
  fetchAddressList()
})
</script>

<style scoped lang="scss">
.profile-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;

  .profile-header {
    margin-bottom: 20px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

    h2 {
      font-size: 24px;
      margin: 0;
      color: #333;
    }
  }

  .profile-content {
    .profile-section {
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      margin-bottom: 20px;
      overflow: hidden;

      .section-header {
        padding: 20px;
        border-bottom: 1px solid #eee;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;

        h3 {
          margin: 0;
          font-size: 18px;
        }
      }

      .section-content {
        padding: 20px;

        .avatar-item {
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: 15px;
          margin-bottom: 30px;
          padding-bottom: 20px;
          border-bottom: 1px solid #eee;

          .avatar-preview {
            position: relative;
            display: flex;
            flex-direction: column;
            align-items: center;

            .avatar-container {
              position: relative;
              cursor: pointer;
              transition: all 0.3s;

              &:hover {
                transform: scale(1.05);

                .avatar-overlay {
                  opacity: 1;
                }
              }

              .avatar-image {
                width: 100px;
                height: 100px;
                border-radius: 50%; /* 确保是正圆形 */
                object-fit: cover;
                border: 2px solid #eee;
                // 当图片为空或加载失败时显示默认背景
                background-color: #ccc;
                display: block;
              }

              .avatar-overlay {
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background-color: rgba(0, 0, 0, 0.6);
                border-radius: 50%;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                opacity: 0;
                transition: opacity 0.3s;

                .upload-icon {
                  font-size: 24px;
                  margin-bottom: 4px;
                }

                .upload-text {
                  color: white;
                  font-size: 12px;
                  text-align: center;
                  line-height: 1.2;
                }
              }
            }

            .avatar-controls {
              display: flex;
              flex-direction: column;
              align-items: center;
              gap: 10px;
              margin-top: 15px;

              .save-avatar-btn,
              .cancel-avatar-btn {
                padding: 8px 16px;
                border: none;
                border-radius: 4px;
                font-size: 12px;
                cursor: pointer;
                transition: all 0.3s;
                min-width: 80px;
              }

              .save-avatar-btn {
                background-color: #409eff;
                color: white;

                &:hover:not(:disabled) {
                  background-color: #3080e0;
                }

                &:disabled {
                  opacity: 0.6;
                  cursor: not-allowed;
                }
              }

              .cancel-avatar-btn {
                background-color: #f56c6c;
                color: white;

                &:hover {
                  background-color: #e64c4c;
                }
              }

              .upload-hint {
                color: #999;
                font-size: 11px;
                text-align: center;
                margin-top: 5px;
                line-height: 1.3;
              }
            }

            .edit-avatar-link {
              text-decoration: none;
              margin-top: 10px;

              .edit-avatar-btn {
                padding: 6px 12px;
                background-color: #409eff;
                color: white;
                border: none;
                border-radius: 4px;
                cursor: pointer;
                font-size: 12px;

                &:hover {
                  background-color: #3080e0;
                }
              }
            }
          }
        }

        .info-grid {
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          gap: 20px;
          margin-bottom: 20px;

          .info-item {
            display: flex;
            flex-direction: column;

            .label {
              color: #666;
              font-weight: 500;
              margin-bottom: 5px;
            }

            .value {
              color: #333;
              font-size: 16px;
            }
          }
        }

        .address-list {
          .address-item {
            padding: 15px;
            border: 1px solid #eee;
            border-radius: 4px;
            margin-bottom: 15px;
            position: relative;

            &.default-address {
              border-color: #409eff;
              background-color: #f0f8ff;
            }

            .address-header {
              display: flex;
              align-items: center;
              margin-bottom: 10px;

              .name {
                font-weight: bold;
                margin-right: 15px;
                font-size: 16px;
              }

              .mobile {
                color: #666;
                margin-right: 10px;
              }

              .default-tag {
                background-color: #409eff;
                color: white;
                padding: 2px 6px;
                border-radius: 3px;
                font-size: 12px;
              }
            }

            .address-detail {
              color: #666;
              line-height: 1.5;
              font-size: 14px;
              margin-bottom: 15px;
            }

            .address-actions {
              display: flex;
              gap: 10px;

              button {
                padding: 5px 10px;
                border: none;
                border-radius: 3px;
                font-size: 12px;
                cursor: pointer;

                &.set-default-btn {
                  background-color: #f0f8ff;
                  color: #409eff;
                  border: 1px solid #409eff;

                  &:hover {
                    background-color: #409eff;
                    color: white;
                  }
                }

                &.edit-address-btn {
                  background-color: #f5f5f5;
                  color: #666;
                  border: 1px solid #ddd;

                  &:hover {
                    background-color: #e6e6e6;
                  }
                }

                &.delete-address-btn {
                  background-color: #fef0f0;
                  color: #f56c6c;
                  border: 1px solid #f56c6c;

                  &:hover {
                    background-color: #f56c6c;
                    color: white;
                  }
                }
              }
            }
          }
        }

        .no-address {
          text-align: center;
          padding: 30px;
          color: #999;
          background-color: #f9f9f9;
          border-radius: 4px;
          margin-bottom: 20px;

          p {
            margin: 0;
            font-size: 16px;
          }
        }

        .section-footer {
          display: flex;
          gap: 10px;

          a {
            text-decoration: none;
          }

          button {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;

            &.edit-btn {
              background-color: #f5f5f5;
              color: #666;

              &:hover {
                background-color: #e6e6e6;
              }
            }

            &.change-btn {
              background-color: #409eff;
              color: white;

              &:hover {
                background-color: #3080e0;
              }
            }
          }
        }
      }
    }
  }
}
</style>

@media (max-width: 768px) { .profile-page { padding: 10px; .profile-content { .profile-section {
.section-content { .info-grid { grid-template-columns: 1fr; } } } } } }
